package controllers

import (
	"2302a_news/cacahe"
	"2302a_news/models"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}
type Msg struct {
	Code int
	Msg  string
	Data interface{}
}

var err error

func (c *UserController) Register() {

	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		res := Msg{
			Code: 0,
			Msg:  "用户名密码不能为空",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var user models.User
	user.Username = username
	if err = user.GetUserByUsername(); err != nil {
		res := Msg{
			Code: 0,
			Msg:  "用户已存在",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	if err = user.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "注册失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code":    500,
		"message": "注册成功",
	}
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户名或密码不能为空",
		}
		c.ServeJSON()
		return
	}
	key := "login_pwd_error_" + username
	count, _ := cacahe.Rdb.Get(cacahe.Ctx, key).Int()
	if count >= 3 {
		cacahe.Rdb.Expire(cacahe.Ctx, key, time.Hour)
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "密码错误超过3次，封禁用户1小时",
		}
		c.ServeJSON()
		return
	}
	user := models.User{
		Username: username,
		Password: password,
	}
	if err = user.GetUserByUsername(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户名不存在",
		}
		c.ServeJSON()
		return
	}
	if user.Password != password {
		cacahe.Rdb.Incr(cacahe.Ctx, key)
		if count == 2 {
			cacahe.Rdb.Expire(cacahe.Ctx, key, time.Hour)
		}
	}
	cacahe.Rdb.Del(cacahe.Ctx, key)
	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "登陆成功",
	}
}
